<template>
    <MiSearch :HistoryName="'listPoduct'" v-model:isSearch="isSearch" v-model:name="ProductModel.name" v-if="isSearch">
    </MiSearch>
    <div class="box">
        <div class="header">
            <img src="@/assets/img/ProductList/icon_arrow_left_darkblack.png" alt="" @click="router.back()">
            <el-input :placeholder="ProductModel.name" class="search-input" :model="ProductModel.name"
                @focus="searchHandler"></el-input>
            <img @click="search" src="@/assets/img/ProductList/tab_images.png" alt="">
        </div>
        <ul class="banner">
            <li :class="{ active: ProductModel.orderCol === 'price' }" @click="changeCol('price')">
                <span>价格</span>
                <div class="icon-arr">
                    <el-icon v-show="ProductModel.orderCol === 'price' && ProductModel.orderDir === 'asc'" size="12px">
                        <ArrowUpBold />
                    </el-icon>
                    <el-icon v-show="ProductModel.orderCol === 'price' && ProductModel.orderDir === 'desc'" size="12px">
                        <ArrowDownBold />
                    </el-icon>
                </div>
            </li>
            <li :class="{ active: ProductModel.orderCol === 'sale' }" @click="changeCol('sale')">
                <span>销量</span>
                <div class="icon-arr">
                    <el-icon v-show="ProductModel.orderCol === 'sale' && ProductModel.orderDir === 'asc'" size="12px">
                        <ArrowUpBold />
                    </el-icon>
                    <el-icon v-show="ProductModel.orderCol === 'sale' && ProductModel.orderDir === 'desc'" size="12px">
                        <ArrowDownBold />
                    </el-icon>
                </div>
            </li>
            <li :class="{ active: ProductModel.orderCol === 'rate' }" @click="changeCol('rate')">
                <span>评论</span>
                <div class="icon-arr">
                    <el-icon v-show="ProductModel.orderCol === 'rate' && ProductModel.orderDir === 'asc'" size="12px">
                        <ArrowUpBold />
                    </el-icon>
                    <el-icon v-show="ProductModel.orderCol === 'rate' && ProductModel.orderDir === 'desc'" size="12px">
                        <ArrowDownBold />
                    </el-icon>
                </div>
            </li>
        </ul>
        <div ref="rootRef" class="container">
            <ul class="info-list">
                <li @click="router.push({ name: 'Details', params: { id: item.id } })" v-for="item in List" :key="item.id"
                    class="info-item">
                    <div>
                        <img :src="item.avatar" alt="">
                    </div>
                    <div class="info">
                        <p class="title">{{ item.name }}</p>
                        <p class="brief">{{ item.brief }}</p>
                        <p> <span style="color: red;">￥{{ item.price }}</span></p>
                        <p class="sale">
                            <span style="padding-right: 20px;">销量{{ item.sale }}</span>
                            <span>好评{{ item.rate }}</span>
                        </p>
                    </div>
                </li>
            </ul>
            <div ref="tipsRef" class="footer">{{ tips }}</div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import MiSearch from '@/components/MiSearch/MiSearch.vue';
import { ProductApi } from '@/api';
import { ref, reactive, shallowRef, onMounted, onUnmounted, computed, watch } from 'vue'
import { ElLoading } from 'element-plus'
import { useRoute, useRouter } from 'vue-router';

const isSearch = ref<Boolean>(false)
const tipsRef = ref()
const rootRef = ref()
const router = useRouter()
const route = useRoute()
const hasMore = ref<Boolean>(true)
const isLoading = ref<Boolean>(false)
// asc升序 : desc降序
const ProductModel = reactive<HttpPayload.Product>({
    cid: 0,
    name: '',
    orderCol: 'price',
    orderDir: 'asc',
    begin: 0,
    pageSize: 6
})
const List = shallowRef<Array<Vm.Product>>([])

// 逻辑部分
let Observer: IntersectionObserver;
onMounted(async () => {
    Observer = new IntersectionObserver(IntersectionObserverCallback, { root: rootRef.value, threshold: [1] })
    // Observer.observe(tipsRef.value)
    ProductModel.cid = parseInt((route.query.cid) as string)
})

const tips = computed(() => {
    if (isLoading.value) return '加载中...'
    else if (List.value.length === 0) return '暂无相关商品，敬请期待...'
    else if (hasMore.value) return "下拉展示更多..."
    else return "已经到底部了."
})


const IntersectionObserverCallback: IntersectionObserverCallback = async (arr) => {
    for (tipsRef.value of arr) {
        if (tipsRef.value.isIntersecting && hasMore.value) {
            // 发ajax，取消并取消监听
            Observer.unobserve(tipsRef.value.target)
            getList(true)
            console.log('触发Observer回调，启动getList(true)')
        }
    }
}

watch(ProductModel, () => {
    rootRef.value.scrollTop = 0
    getList(false)
})

watch(List, () => {
    console.log(`hasMore的值${hasMore.value}`)
    if (hasMore.value) {
        Observer.observe(tipsRef.value)
        isLoading.value = false
    }
})


const getList = async (isMore: boolean) => {
    isLoading.value = true;

    const loadingInstance = ElLoading.service({ text: "loading..", background: 'rgba(255,255,255,0.5)' })

    const list = await ProductApi.getlist(isMore ? { ...ProductModel, begin: List.value.length } : ProductModel)
    if (list.length < 6) {
        hasMore.value = false
    } else {
        hasMore.value = true
    }
    await new Promise((resolve: any): void => {
        setTimeout((): void => {
            List.value = isMore ? List.value.concat(list) : list
            isLoading.value = false
            loadingInstance.close()
            resolve()
        }, 500)
    })

}


const search = async () => {
    isSearch.value = true
}
const searchHandler = () => {
    isSearch.value = true
}


const changeCol = async (col: string) => {
    if (ProductModel.orderCol === col) {
        ProductModel.orderDir === 'asc' ? ProductModel.orderDir = 'desc' : ProductModel.orderDir = 'asc'
    } else {
        ProductModel.orderCol = col
    }
}
onUnmounted(() => {
    Observer.disconnect()
})
</script>
<style lang="stylus" scoped>
.box
    width 100%
    height 100%
    display flex
    flex-direction column

.header
    height 12vw
    display flex
    flex-shrink 0
    justify-content space-evenly
    align-items center
    border-bottom 1px solid rgb(239, 239, 240);

.search-input .el-input__wrapper
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 18px;
    height: 36px;

.header img:first-child
    height 32px

.header img:last-child
        height 30px

.el-input
    width 281px
    

.banner
    display flex
    flex-shrink 0
    height 36px
    justify-content space-evenly
    border-bottom 1px solid rgb(239, 239, 240);

.banner li
    display flex
    align-items center   

.banner li.active
    color: rgb(180, 115, 31)
    font-weight 600

.icon-arr
    display flex
    flex-direction column
    margin-left 5px

.info-list img
    width 126px
    height 126px



.info-item
    display flex
    padding 12px
    
.info
    display flex
    flex-direction column
    justify-content space-evenly

.info-item div:last-child
    flex-grow 1

.title
    color: rgb(51, 51, 51);
    font-size: 14px;
    line-height: 19px;

.brief
    font-size 12px
    
.sale
    display flex
    color #333
    font-size 12px

.container
    flex-grow 1
    overflow auto

.container::-webkit-scrollbar
    width 0
.footer 
    height 100px
    line-height 20px
    font-size 12px
    color: rgb(136, 136, 136);
    text-align center
</style>